package com.huiminpay.merchant.controller;

import com.alibaba.fastjson.JSONObject;
import com.aliyun.oss.OSS;
import com.aliyun.oss.OSSClientBuilder;
import com.aliyun.oss.model.PutObjectRequest;
import com.huiminpay.common.cache.domain.BusinessException;
import com.huiminpay.common.cache.domain.CommonErrorCode;
import com.huiminpay.common.cache.domain.PageVO;
import com.huiminpay.common.cache.util.PhoneUtil;
import com.huiminpay.common.cache.util.QRCodeUtil;
import com.huiminpay.common.cache.util.StringUtil;
import com.huiminpay.merchant.common.SecurityUtil;
import com.huiminpay.merchant.convert.MerchantConvert;
import com.huiminpay.merchant.service.SmsService;
import com.huiminpay.merchant.vo.MerchantVo;
import com.huiminpay.merchant.vo.RegMchVo;
import com.huiminpay.transaction.api.dto.QrcodeDto;
import com.huiminpay.transaction.api.service.ITransactionService;
import com.yh.merchant.api.IMerchantService;
import com.yh.merchant.api.Service.IStoreService;
import com.yh.merchant.api.dto.MerchantDTO;
import com.yh.merchant.api.dto.QueryStoreDTO;
import com.yh.merchant.api.dto.StoreDTO;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiOperation;
import org.apache.dubbo.config.annotation.Reference;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.http.*;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.client.RestTemplate;
import org.springframework.web.multipart.MultipartFile;

import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;

@RestController
@Api(value = "商户相关操作",tags = "商户相关操作",description = "商户的CRUD")
public class MerchantController {

    @Reference
    IMerchantService iMerchantService;
    @Reference
    IStoreService iStoreService;
    @Reference
    ITransactionService transactionService;
    @Autowired
    SmsService smsServiceImpl;
    @Autowired
    OSS oss;
    @Value("${aliyun.oss.domain}")
    private String domain;
    @Value("${aliyun.oss.bucketName}")
    private String bucketName;

    @PostMapping("/upload")
    @ApiOperation("文件上传")
    public Object upload(@RequestParam("file")MultipartFile file){
        //非空校验
        if (file==null){
            throw new BusinessException(CommonErrorCode.E_200201);
        }
        //用当前时间戳当文件名  或UUID 来保证文件名不重复
        Long name = System.currentTimeMillis();
        String originalFilename = file.getOriginalFilename();
        String extType = originalFilename.substring(originalFilename.lastIndexOf("."));
        //时间戳加上扩展名 当文件名
        String fileName = name+extType;
        try {
//            创建PutObjectRequest对象。
//// 依次填写Bucket名称（例如examplebucket）和Object完整路径（例如exampledir/exampleobject.txt）。Object完整路径中不能包含Bucket名称。
            PutObjectRequest putObjectRequest = new PutObjectRequest(bucketName, fileName,file.getInputStream());
            //上传文件
            oss.putObject(putObjectRequest);
        } catch (IOException e) {
            e.printStackTrace();
            throw new BusinessException(CommonErrorCode.E_100106);

        }
//        oss.shutdown();

        return domain+fileName;
    }

    @PostMapping("/my/merchants/save")
    @ApiOperation("商户资质申请")
    public Object applay(@RequestBody MerchantVo merchantVo){
        //1.非空校验

        //2.对象转换
        MerchantDTO merchantDTO = MerchantConvert.INSTANCE.vo2dto2(merchantVo);
        //3.更新数据
        //不相信前端传的数据  自己从模拟登录的用户获取id
        Long merchantId = SecurityUtil.getMerchantId();
        merchantDTO.setId(merchantId);
        merchantDTO = iMerchantService.applay(merchantDTO);
        return merchantDTO;
    }



    @ApiOperation("根据商户id查询商户信息")
    @ApiImplicitParam(name="id",value = "商户ID",example = "1",dataType = "Long")//paramType常用： body path query
    @GetMapping("/merchants/{id}")
    public MerchantVo queryMerchantById(@PathVariable("id") Long id){
        MerchantDTO merchantDTO = iMerchantService.queryMerchantById(id);
        return MerchantConvert.INSTANCE.dto2vo2(merchantDTO);
    }
    @ApiOperation("获取登录用户的商户信息")
    @GetMapping(value="/my/merchants")
    public MerchantDTO getMyMerchantInfo(){
        // 从token 中获取商户id
        Long merchantId = SecurityUtil.getMerchantId();
        MerchantDTO merchant = iMerchantService.queryMerchantById(merchantId);
        return merchant;
    }


    @GetMapping("sms")
    @ApiOperation("短信发送")
    @ApiImplicitParam(name="mobile",value = "手机号",example = "134****8745",dataType = "String")//paramType常用： body path query

    public Object sendSms(String mobile){
        return smsServiceImpl.sendSms(mobile);
    }

    @PostMapping("/merchants/register")
    @ApiOperation("注册商户")
    public Object register(@RequestBody RegMchVo regMchVo){
        //1.非空
        if(StringUtil.isEmpty(regMchVo.getMobile())){
//            throw new RuntimeException("手机号为空");
            throw  new BusinessException(CommonErrorCode.E_200230);
        }
        if(StringUtil.isEmpty(regMchVo.getVerifiyCode())){
//            throw new RuntimeException("验证码为空");
            throw  new BusinessException(CommonErrorCode.E_100103);
        }
        if(StringUtil.isEmpty(regMchVo.getUsername())){
//            throw new RuntimeException("用户名为空");
            throw  new BusinessException(CommonErrorCode.E_200231);
        }
        if(StringUtil.isEmpty(regMchVo.getPassword())){
//            throw new RuntimeException("密码为空");
            throw  new BusinessException(CommonErrorCode.E_200232);
        }
        if(StringUtil.isEmpty(regMchVo.getVerifiyKey())){
//            throw new RuntimeException("key为空");
            throw  new BusinessException(CommonErrorCode.E_100107);
        }
        //2.验证码校验
        if (!PhoneUtil.isMatches(regMchVo.getMobile())){
//            throw new RuntimeException("手机号格式错误");
            throw  new BusinessException(CommonErrorCode.E_200224);
        }
        Boolean aBoolean = smsServiceImpl.verifyCode(regMchVo.getVerifiyCode(), regMchVo.getVerifiyKey());
        if (!aBoolean){
//            throw new RuntimeException("验证码过期或者错误");
            throw  new BusinessException(CommonErrorCode.E_100102);
        }

        //3.保存数据
//        MerchantDTO merchantDTO = new MerchantDTO();
//        BeanUtils.copyProperties(regMchVo,merchantDTO);
        //对象转换
        MerchantDTO merchantDTO = MerchantConvert.INSTANCE.vo2dto(regMchVo);


        return iMerchantService.reg(merchantDTO);
    }
    @ApiOperation("分页条件查询商户下门店")
    @PostMapping("/my/stores/merchants/page")
    public PageVO<StoreDTO> queryStoreByPage(@RequestParam Integer pageNo, @RequestParam Integer
            pageSize){

        Long merchantId = SecurityUtil.getMerchantId();//获取商户id
        QueryStoreDTO queryStoreDTO = new QueryStoreDTO(pageNo, pageSize, merchantId);

        return iStoreService.queryStoreByPage(queryStoreDTO);
    }

    /**
     *
     * @param appId 是为了获取支付渠道参数
     * @param storeId 门店
     * @return
     * @throws BusinessException
     */
    @ApiOperation("生成商户应用门店二维码")
    @GetMapping(value = "/my/apps/{appId}/stores/{storeId}/app-store-qrcode")
    public String createCScanBStoreQRCode(@PathVariable String appId, @PathVariable Long storeId) throws BusinessException, IOException {

        //二维码URL
        String qrUrl = null; //抽取 唯一的时候放服务层  不唯一的时候放应用层
        Long merchantId = SecurityUtil.getMerchantId();//获取商户id

        QrcodeDto qrcodeDto = new QrcodeDto();
        qrcodeDto.setAppId(appId);
        qrcodeDto.setMerchantId(merchantId);
        qrcodeDto.setStoreId(storeId);
        qrcodeDto.setQrUrl(qrUrl);
        //生成二维码URL连接  入口地址＋参数
        String url = transactionService.creatQrurl(qrcodeDto);
        String qrCode = new QRCodeUtil().createQRCode(url, 200, 200);

        return qrCode ;
    }
    @ApiOperation("生成商户应用门店二维码")
    @PostMapping()




    @GetMapping("test")
    public Object test(){
//        // yourEndpoint填写Bucket所在地域对应的Endpoint。以华东1（杭州）为例，Endpoint填写为https://oss-cn-hangzhou.aliyuncs.com。
//        String endpoint = "oss-cn-zhangjiakou.aliyuncs.com";
//// 阿里云账号AccessKey拥有所有API的访问权限，风险很高。强烈建议您创建并使用RAM用户进行API访问或日常运维，请登录RAM控制台创建RAM用户。
//        String accessKeyId = "LTAI5tMsXDMwPaQbpX29arkp";
//        String accessKeySecret = "yS2YDpLqvuQSwCu8a6FqrH6TOQk8Hu";
//        String bucketName = "fhs0728";
//
//// 创建OSSClient实例。
//        OSS ossClient = new OSSClientBuilder().build(endpoint, accessKeyId, accessKeySecret);
//
//// 填写字符串。
//        String content = "Hello 凤凰山";
//
//// 创建PutObjectRequest对象。
//// 依次填写Bucket名称（例如examplebucket）和Object完整路径（例如exampledir/exampleobject.txt）。Object完整路径中不能包含Bucket名称。
//        PutObjectRequest putObjectRequest = new PutObjectRequest(bucketName, "2021/07/a.txt", new ByteArrayInputStream(content.getBytes()));
//
//// 如果需要上传时设置存储类型和访问权限，请参考以下示例代码。
//// ObjectMetadata metadata = new ObjectMetadata();
//// metadata.setHeader(OSSHeaders.OSS_STORAGE_CLASS, StorageClass.Standard.toString());
//// metadata.setObjectAcl(CannedAccessControlList.Private);
//// putObjectRequest.setMetadata(metadata);
//
//// 上传字符串。
//        ossClient.putObject(putObjectRequest);
//
//// 关闭OSSClient。
//        ossClient.shutdown();

        return null;
    }



}
